package com.example.yskjproject.view.dialog;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RadioButton;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.example.yskjproject.R;
import com.example.yskjproject.http.Urls;
import com.example.yskjproject.http.callback.JsonCallback;
import com.example.yskjproject.model.LzyResponse;
import com.example.yskjproject.model.PayModel;
import com.example.yskjproject.utils.DateUtils;
import com.example.yskjproject.utils.QRCodeUtil;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.tencent.qcloud.tuicore.util.ToastUtil;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * PayDialog   支付界面
 * <p>
 * 作者：zx
 * 创建时间：2024/5/22
 */
public class PayDialog extends Dialog implements View.OnClickListener {

    private Context context;
    private Gson gson = new Gson();
    private String studioId;
    private AppCompatImageView payCode, imgColose;
    private String endTime = null;
    private MyHandler handler;
    private RadioButton rbWechat;
    private RadioButton rbBalance;
    private RadioButton rbToken;
    private AppCompatTextView tvWxInfo;
    private AppCompatTextView tvWxInfo2;
    private String payType = "wechat";

    public PayDialog(@NonNull Context context, String studioId) {
        super(context);
        this.context = context;
        this.studioId = studioId;
        setContentView(R.layout.pay_dialog);
        payCode = findViewById(R.id.pay_code);
        imgColose.setOnClickListener(dis -> dismiss());
        tvWxInfo = findViewById(R.id.tv_wx_info);
        tvWxInfo2 = findViewById(R.id.tv_wx_info2);

        // 获取 RadioButton 实例
        rbWechat = findViewById(R.id.rb_wechat_pay);
        rbBalance = findViewById(R.id.rb_balance_pay);
        rbToken = findViewById(R.id.rb_token_pay);

        rbBalance.setOnClickListener(this);
        rbWechat.setOnClickListener(this);
        rbToken.setOnClickListener(this);


    }

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        if (window != null) {
            WindowManager.LayoutParams layoutParams = window.getAttributes();
            layoutParams.gravity = Gravity.CENTER;
            layoutParams.width = (int) (getContext().getResources().getDisplayMetrics().widthPixels); // 设置宽度
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            window.setAttributes(layoutParams);
        }
        setCanceledOnTouchOutside(false);
        handler = new MyHandler(this);
        setDateInfo(studioId);
    }

    /**
     * 设置我的工作室内容
     */
    @SuppressLint("NotifyDataSetChanged")
    private void setDateInfo(String studioId) {
        Map<String, Object> jsonParams = new HashMap<>();
        jsonParams.put("studio_id", Integer.valueOf(studioId));
        jsonParams.put("pay_type", payType);
        String paramsDate = gson.toJson(jsonParams);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), paramsDate);
        OkGo.<LzyResponse<PayModel>>post(Urls.ORDER_CREATE).upRequestBody(requestBody).execute(new JsonCallback<LzyResponse<PayModel>>() {
            @SuppressLint("SimpleDateFormat")
            @Override
            public void onSuccess(Response<LzyResponse<PayModel>> response) {
                PayModel payModel = response.body().data;
                if (payModel != null) {
                    Glide.with(context).load(payModel.getPay_info().getPay_url())
                            .apply(RequestOptions.bitmapTransform(new RoundedCorners(40))) // 圆角半径
                            .into(payCode);
                    endTime = payModel.getPay_info().getExpire_time();
                    if (handler != null) {
                        handler.sendEmptyMessage(0);
                    }
                }
            }

            @Override
            public void onError(Response<LzyResponse<PayModel>> response) {
                super.onError(response);
                ToastUtil.toastShortMessage(response.getException().getMessage());
            }
        });
    }

    @Override
    public void dismiss() {
        super.dismiss();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rb_wechat_pay:
                rbWechat.setChecked(true);
                rbBalance.setChecked(false);
                rbToken.setChecked(false);
                payCode.setVisibility(View.VISIBLE);
                tvWxInfo.setVisibility(View.VISIBLE);
                tvWxInfo2.setVisibility(View.VISIBLE);
                payType = "wechat";
                break;
            case R.id.rb_balance_pay:
                rbWechat.setChecked(false);
                rbBalance.setChecked(true);
                rbToken.setChecked(false);
                payCode.setVisibility(View.GONE);
                tvWxInfo.setVisibility(View.GONE);
                tvWxInfo2.setVisibility(View.GONE);
                payType = "balance";
                break;
            case R.id.rb_token_pay:
                rbWechat.setChecked(false);
                rbBalance.setChecked(false);
                rbToken.setChecked(true);
                payCode.setVisibility(View.GONE);
                tvWxInfo.setVisibility(View.GONE);
                tvWxInfo2.setVisibility(View.GONE);
                payType = "virtual_coin";
                break;
        }

    }

    private static class MyHandler extends Handler {
        private final WeakReference<PayDialog> weakReference;

        public MyHandler(PayDialog payDialog) {
            this.weakReference = new WeakReference<>(payDialog);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            PayDialog payDialog = weakReference.get();
            if (payDialog != null) {
                if (msg.what == 0) {
                    try {
                        long endTimeTimestamp = DateUtils.stringToTimeStamp(payDialog.endTime);
                        if (endTimeTimestamp - System.currentTimeMillis() < 10000) {
                            payDialog.setDateInfo(payDialog.studioId);
                        } else {
                            if (payDialog.handler != null) {
                                payDialog.handler.removeMessages(0);
                                payDialog.handler.sendEmptyMessageDelayed(0, 5000);
                            }
                        }
                    } catch (Exception e) {
                        // 处理异常，例如记录日志
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
